<?php
/**
 * Created by Silent Night.
 * User: Silent Night
 * Date: 2017/9/26
 * Time: 11:13
 */

namespace app\api\controller;

use think\Controller;
use app\api\model;

class Order extends Controller
{

    public function index()
    {
//       echo $startTime = strtotime("2019-01-23 17:44:22");
//       echo date("Y-m-d H:i:s",$startTime);
    }


    public function alipay_n()
    {

        $string = json_encode($_REQUEST, true);
        file_put_contents("/www/wwwroot/default/chun.text", $string);

        $flag = alipay_notify_check();
        file_put_contents("/www/wwwroot/default/chun1.text", $flag);
//        if ($flag == false) {
//            echo "fail";
//            exit;
//        }
        $auth_app_id = $_POST['auth_app_id'];
        $trade_no = $_POST['trade_no'];//订单号支付宝
        $out_trade_no = $_POST['out_trade_no'];//订单号我们订单
        $trade_status = $_POST['trade_status'];//支付状态
        $money = $_POST['buyer_pay_amount'];//支付金额
        $config =config("alipayConfig");
        if ($auth_app_id != $config['appId']) {//判断商户
            echo "fail";
            exit;
        }
        if ($trade_status != "TRADE_SUCCESS") {//判断支付状态

            echo "fail";
            exit;
        }
        if (empty($trade_no)) {
            echo "fail";
            exit;
        }
        if (empty($out_trade_no)) {
            echo "fail";
            exit;
        }
        $payOrderMode = new \app\admin\model\PayOrder();
        $res = $payOrderMode->getDataForWhere(array(
            'order_sn' => $out_trade_no
        ));
        if (empty($res))//订单号不存在
        {
            echo "fail";
            exit;
        }
        if ($res['stat'] == 1)//
        {
            echo "fail";
            exit;
        }

        if ($res['money'] != $money)//支付金额不正确
        {
            exit;
        }

        if (empty($res['uid']))//订单表中用户不存在
        {
            echo "fail";
            exit;
        }

        $userModel = new \app\admin\model\User();
        $userInfo = $userModel->getDataForWhere(array(
            'id' => $res['uid']
        ));

        if (empty($userInfo)) {//用户不存在
            echo "fail";
            exit;
        }
        if ($res['ty'] == 0) {//挑战
            //get classlist info
            $classlistInfo = getClasslistInfo($res['classid']);

            //修改订单状态
            $flagRest = $payOrderMode->updateData(array('stat' => 1, 'ptime' => date("Y-m-d:H:i:s")),
                $res['id']);
            if ($flagRest) {
                //支付成功，写入报名
                if (isJoinInClass($userInfo['id'], $classlistInfo['id']) == 0) {
                    $data = array(
                        'uid' => $userInfo['id'],
                        'classid' => $classlistInfo['id'],
                        'payno' => $res['order_sn'],
                        'ctime' => date('Y-m-d H:i:s'),
                        'stat' => 0,
                        'money' => $res['money'],
                        'price' => $res['price'],
                        'num' => $res['num'],
                        'ty' => 0//0是课程 1是商品
                    );
                    $result = joinInClass($data);//加入课程
                    if ($result) {
                        //写入打卡计划
                        addPlanCheckIn($userInfo['id'], $classlistInfo);//加入打卡计划
                        //写入金额明细,无金额变动，无需写入金额变动明细
                        //addUserMoneyDetail($userInfo['id'], $res['money'], 1, '挑战扣款', $res['order_sn']);
                        //课程增加奖池 和购买人数
                        addClasslistTotleMoneyAndNum($classlistInfo['id'], $res['money'], $res['num']);
                    }
                }
                echo 'success';
                exit;
            } else {
                echo "fail";
                exit;
            }
        } else//商品
        {
            $flagRest = $payOrderMode->updateData(array('stat' => 1, 'status' => 1, 'ptime' => date("Y-m-d:H:i:s")),
                $res['id']);
            if ($flagRest) {
                addOrderTrackLog(array(
                    'ctime'=>date("Y-m-d H:i:s"),
                    'order_sn'=>$res['order_sn'],
                    'op_uid'=>$userInfo['id'],
                    'op_username'=>$userInfo['uname']."[".$userInfo['nickname']."]",
                    'act'=>"支付宝支付",
                ));
                echo 'success';
                exit;
            } else {
                echo "fail";
                exit;
            }
        }
    }


    /**
     * 获取我的订单列表接口
     */
    public function lists()
    {
        $auth = trim(input("request.auth"));//用户auth
        $status = trim(input("request.status"));//帖子ID
        if (empty($status)) {
            $status = 0;
        }
        $userInfo = checkLoginExp($auth);

        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }

        $pagesize = trim(input("pagesize"));//每页条数

        if (!empty($pagesize)) {
            $this->pagesize = $pagesize;
        }

        if (!in_array($status, [-1, 0, 1, 2, 3,4])) {
            $return = ['err' => 1, 'msg' => '参数错误,订单状态不正确', 'devMsg' => '获取失败，参数错误[ty]'];
            return json($return);
        }


        $w = array();

        $w['uid'] = $userInfo['id'];
        $w['is_delete'] = 0;
        if ($status >= 0) {
            $w['status'] = $status;
        }
        $w['ty'] = 1;

        $model = new \app\admin\model\PayOrder();
        $lists = $model->lists($w, $this->pagesize);

        $lists = $lists['data'];
        $lists = changeUidToUserinfoForLists($lists, 'uid');//获取发帖人信息
        foreach ($lists as $key => $val) {
            $lists[$key]['goodLists'] = getGoodListByOrdersn($val['order_sn']);
        }
        $return['err'] = 0;
        $return['msg'] = '获取成功';
        $return['data'] = $lists;
        return json($return);
    }




    /**
     * 删除我的订单
     * @return \think\response\Json
     */
    public function delMyOrder()
    {
        $auth = trim(input("request.auth"));//用户auth
        $order_sn = trim(input("request.order_sn"));//帖子ID
        $userInfo = checkLoginExp($auth);
        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '操作失败,未登录', 'devMsg' => '操作失败，参数错误[auth]'];
            return json($return);
        }
        if (empty($order_sn)) {
            $return = ['err' => 2, 'msg' => '操作失败,订单号为空', 'devMsg' => '操作失败，参数错误[order_sn]'];
            return json($return);
        }
        $payOrderMode = new \app\admin\model\PayOrder();
        $orderInfo = $payOrderMode->getDataForWhere(array(
            'order_sn' => $order_sn
        ));
        if (empty($orderInfo))//订单号不存在
        {
            $return = ['err' => 3, 'msg' => '操作失败,订单不存在', 'devMsg' => '操作失败，参数错误[order_sn]'];
            return json($return);
        }

        if ($orderInfo['uid'] != $userInfo['id']) {
            $return = ['err' => 4, 'msg' => '操作失败，对不起，您无权操作该订单', 'devMsg' => '操作失败'];
            return json($return);
        }
        if ($orderInfo['stat'] == 1) {
            $return = ['err' => 4, 'msg' => '操作失败，对不起，该订单已经付款，不能够删除了', 'devMsg' => '操作失败'];
            return json($return);
        }
        if ($orderInfo['is_delete'] == 1) {
            $return = ['err' => 5, 'msg' => '操作失败，对不起，该订单已经不存在', 'devMsg' => '操作失败'];
            return json($return);
        }
        $res = $payOrderMode->updateDataForWhere(array('is_delete' => 1), array('id' => $orderInfo['id']));
        if ($res || $res == 0) {
            addOrderTrackLog(array(
                'ctime'=>date("Y-m-d H:i:s"),
                'order_sn'=>$orderInfo['order_sn'],
                'op_uid'=>$userInfo['id'],
                'op_username'=>$userInfo['uname']."[".$userInfo['nickname']."]",
                'act'=>"删除订单",
            ));
            $return = ['err' => 0, 'msg' => '操作成功', 'devMsg' => '操作成功'];
            return json($return);
        } else {
            $return = ['err' => 1, 'msg' => '操作失败', 'devMsg' => '操作失败'];
            return json($return);
        }

    }


    public function orderInfo()
    {
        $auth = trim(input("request.auth"));//用户auth
        $order_sn = trim(input("request.order_sn"));//帖子ID
        $userInfo = checkLoginExp($auth);
        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }
        if (empty($order_sn)) {
            $return = ['err' => 2, 'msg' => '获取失败,订单号为空', 'devMsg' => '获取失败，参数错误[order_sn]'];
            return json($return);
        }
        $payOrderMode = new \app\admin\model\PayOrder();
        $orderInfo = $payOrderMode->getDataForWhere(array(
            'order_sn' => $order_sn
        ));
        if (empty($orderInfo))//订单号不存在
        {
            $return = ['err' => 3, 'msg' => '获取失败,订单不存在', 'devMsg' => '获取失败，参数错误[order_sn]'];
            return json($return);
        }

        if ($orderInfo['uid'] != $userInfo['id']) {
            $return = ['err' => 4, 'msg' => '获取失败，对不起，您无权操作该订单', 'devMsg' => '获取失败'];
            return json($return);
        }

        if ($orderInfo['is_delete'] == 1) {
            $return = ['err' => 5, 'msg' => '获取失败，对不起，该订单已经不存在', 'devMsg' => '获取失败'];
            return json($return);
        }

        if ($orderInfo['ty'] == 0) {
            $return = ['err' => 0, 'msg' => '获取成功', 'data' => $orderInfo];
            return json($return);
        }

        $orderInfo['goodLists'] = getGoodListByOrdersn($orderInfo['order_sn']);
        $return = ['err' => 0, 'msg' => '获取成功', 'data' => $orderInfo];
        return json($return);
    }


    /**
     * 催催发货
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function deliverGoods()
    {
        $auth = trim(input("request.auth"));//用户auth
        $order_sn = trim(input("request.order_sn"));//帖子ID
        $userInfo = checkLoginExp($auth);
        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '获取失败,未登录', 'devMsg' => '获取失败，参数错误[auth]'];
            return json($return);
        }
        if (empty($order_sn)) {
            $return = ['err' => 2, 'msg' => '获取失败,订单号为空', 'devMsg' => '获取失败，参数错误[order_sn]'];
            return json($return);
        }
        $payOrderMode = new \app\admin\model\PayOrder();
        $orderInfo = $payOrderMode->getDataForWhere(array(
            'order_sn' => $order_sn
        ));
        if (empty($orderInfo))//订单号不存在
        {
            $return = ['err' => 3, 'msg' => '获取失败,订单不存在', 'devMsg' => '获取失败，参数错误[order_sn]'];
            return json($return);
        }

        if ($orderInfo['uid'] != $userInfo['id']) {
            $return = ['err' => 4, 'msg' => '获取失败，对不起，您无权操作该订单', 'devMsg' => '获取失败'];
            return json($return);
        }

        if ($orderInfo['is_delete'] == 1) {
            $return = ['err' => 5, 'msg' => '获取失败，对不起，该订单已经不存在', 'devMsg' => '获取失败'];
            return json($return);
        }

        if ($orderInfo['ty'] == 0) {
            $return = ['err' => 6, 'msg' => '该订单不是商品订单，无需发货', 'devMsg' => "该订单无需发货"];
            return json($return);
        }
        if ($orderInfo['status'] == 0) {
            $return = ['err' => 6, 'msg' => '该订单未付款', 'devMsg' => "该订单未付款"];
            return json($return);
        }

        if ($orderInfo['status'] == 2) {
            $return = ['err' => 6, 'msg' => '该订单已发货', 'devMsg' => "该订单已发货"];
            return json($return);
        }

        if ($orderInfo['status'] == 3) {
            $return = ['err' => 6, 'msg' => '该订单已发货，并完成', 'devMsg' => "该订单已发货，并完成"];
            return json($return);
        }

        if ($orderInfo['status'] == 4) {
            $return = ['err' => 6, 'msg' => '该订单已取消', 'devMsg' => "该订单已取消"];
            return json($return);
        }
        $cdfh_num = 1;
        if ($orderInfo['cdfh_num']) {
            $cdfh_num = $cdfh_num + $orderInfo['cdfh_num'];
        }
        $cdfh_time = date("Y-m-d H:i:s");
        $res = $payOrderMode->updateDataForWhere(array('cdfh_num' => $cdfh_num, 'cdfh_time' => $cdfh_time), array('id' => $orderInfo['id']));
        if ($res || $res == 0) {
            addOrderTrackLog(array(
                'ctime'=>date("Y-m-d H:i:s"),
                'order_sn'=>$orderInfo['order_sn'],
                'op_uid'=>$userInfo['id'],
                'op_username'=>$userInfo['uname']."[".$userInfo['nickname']."]",
                'act'=>"催促发货",
            ));
            $return = ['err' => 0, 'msg' => '操作成功', 'devMsg' => '操作成功'];
            return json($return);
        } else {
            $return = ['err' => 1, 'msg' => '操作失败', 'devMsg' => '操作失败'];
            return json($return);
        }
    }

    /**
     * 确认收货
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function confirmOrder()
    {
        $auth = trim(input("request.auth"));//用户auth
        $order_sn = trim(input("request.order_sn"));//帖子ID
        $userInfo = checkLoginExp($auth);
        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '操作失败,未登录', 'devMsg' => '操作失败，参数错误[auth]'];
            return json($return);
        }
        if (empty($order_sn)) {
            $return = ['err' => 2, 'msg' => '操作失败,订单号为空', 'devMsg' => '操作失败，参数错误[order_sn]'];
            return json($return);
        }
        $payOrderMode = new \app\admin\model\PayOrder();
        $orderInfo = $payOrderMode->getDataForWhere(array(
            'order_sn' => $order_sn
        ));
        if (empty($orderInfo))//订单号不存在
        {
            $return = ['err' => 3, 'msg' => '操作失败,订单不存在', 'devMsg' => '操作失败，参数错误[order_sn]'];
            return json($return);
        }

        if ($orderInfo['uid'] != $userInfo['id']) {
            $return = ['err' => 4, 'msg' => '操作失败，对不起，您无权操作该订单', 'devMsg' => '操作失败'];
            return json($return);
        }

        if ($orderInfo['is_delete'] == 1) {
            $return = ['err' => 5, 'msg' => '获取失败，对不起，该订单已经不存在', 'devMsg' => '获取失败'];
            return json($return);
        }

        if ($orderInfo['ty'] == 0) {
            $return = ['err' => 6, 'msg' => '该订单不是商品订单确认收货，', 'devMsg' => "该订单确认收货"];
            return json($return);
        }
        if ($orderInfo['status'] == 0) {
            $return = ['err' => 6, 'msg' => '该订单未付款', 'devMsg' => "该订单未付款"];
            return json($return);
        }

        if ($orderInfo['status'] == 1) {
            $return = ['err' => 6, 'msg' => '该订单尚未发货', 'devMsg' => "该订单尚未发货"];
            return json($return);
        }

        if ($orderInfo['status'] == 3) {
            $return = ['err' => 6, 'msg' => '该订单已完成', 'devMsg' => "该订单已完成"];
            return json($return);
        }

        if ($orderInfo['status'] == 4) {
            $return = ['err' => 6, 'msg' => '该订单已取消', 'devMsg' => "该订单已取消"];
            return json($return);
        }

        $res = $payOrderMode->updateDataForWhere(array('status' => 3), array('id' => $orderInfo['id']));
        if ($res || $res == 0) {
            addOrderTrackLog(array(
                'ctime'=>date("Y-m-d H:i:s"),
                'order_sn'=>$orderInfo['order_sn'],
                'op_uid'=>$userInfo['id'],
                'op_username'=>$userInfo['uname']."[".$userInfo['nickname']."]",
                'act'=>"确认收货",
            ));
            $return = ['err' => 0, 'msg' => '操作成功', 'devMsg' => '操作成功'];
            return json($return);
        } else {
            $return = ['err' => 1, 'msg' => '操作失败', 'devMsg' => '操作失败'];
            return json($return);
        }
    }

    /**查询物流信息
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function selectWuliuInfo()
    {
        $auth = trim(input("request.auth"));//用户auth
        $order_sn = trim(input("request.order_sn"));//帖子ID
        $userInfo = checkLoginExp($auth);
        if (empty($userInfo)) {
            $return = ['err' => 1, 'msg' => '操作失败,未登录', 'devMsg' => '操作失败，参数错误[auth]'];
            return json($return);
        }
        if (empty($order_sn)) {
            $return = ['err' => 2, 'msg' => '操作失败,订单号为空', 'devMsg' => '操作失败，参数错误[order_sn]'];
            return json($return);
        }
        $payOrderMode = new \app\admin\model\PayOrder();
        $orderInfo = $payOrderMode->getDataForWhere(array(
            'order_sn' => $order_sn
        ));
        if (empty($orderInfo))//订单号不存在
        {
            $return = ['err' => 3, 'msg' => '操作失败,订单不存在', 'devMsg' => '操作失败，参数错误[order_sn]'];
            return json($return);
        }

        if ($orderInfo['uid'] != $userInfo['id']) {
            $return = ['err' => 4, 'msg' => '操作失败，对不起，您无权操作该订单', 'devMsg' => '操作失败'];
            return json($return);
        }

        if ($orderInfo['is_delete'] == 1) {
            $return = ['err' => 5, 'msg' => '获取失败，对不起，该订单已经不存在', 'devMsg' => '获取失败'];
            return json($return);
        }

        if ($orderInfo['ty'] == 0) {
            $return = ['err' => 6, 'msg' => '该订单不是商品订单无物流信息', 'devMsg' => "该订单不是商品订单无物流信息"];
            return json($return);
        }
        if ($orderInfo['status'] == 0) {
            $return = ['err' => 6, 'msg' => '该订单未付款', 'devMsg' => "该订单未付款"];
            return json($return);
        }

        if ($orderInfo['status'] == 1) {
            $return = ['err' => 6, 'msg' => '该订单尚未发货', 'devMsg' => "该订单尚未发货"];
            return json($return);
        }
        if (empty($orderInfo['express_no']) || empty($orderInfo['express_type'])) {
            $return = ['err' => 6, 'msg' => '该订单暂未跟踪到物流信息', 'devMsg' => "该订单暂未跟踪到物流信息"];
            return json($return);
        }


        $selectResult = selectWuliuMsg($orderInfo['express_type'],$orderInfo['express_no']);
        if($selectResult['data'])
        {
            $res=array();
            $res['data']=array(
                'wuliuList'=>$selectResult['data'],
                'orderInfo'=>$orderInfo,
            );
            $res['msg'] = '获取成功';
            $res['err'] = 0;
            return json($res);
        }
        else
        {
            $res=array();
            $res['data']=array(
                'wuliuList'=>array(),
                'orderInfo'=>$orderInfo,
            );
            $res['msg'] = '获取成功';
            $res['err'] = 0;
            return json($res);
        }

    }

}